package com.lanhai.crowd.mvc.interceptor;

import com.lanhai.crowd.constant.CrowdConstant;
import com.lanhai.crowd.entity.Admin;
import com.lanhai.crowd.exception.AccessForbiddenException;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * 登录拦截器类
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {


    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        // 1.获取HttpSession对象
        HttpSession session = httpServletRequest.getSession();

        // 2.从session对象中取出CrowdConstant.ATTR_NAME_LOGIN_ADMIN
        Admin loginAdmin = (Admin) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN);

        // 3.检查是否存在admin对象
        if(Objects.isNull(loginAdmin))
            throw new AccessForbiddenException(CrowdConstant.MESSAGE_NOT_ACCESS_FORBIDDEN);

        // 4.存在admin对象则允许通行
        return true;
    }


}
